﻿// 功能：地图下载器
// 描述：
// 作者：温伟鹏
// 日期：2010/10/22 16:20:09

using System;
using System.IO;
using System.Net;
using MeizuSDK.Core;
using System.Collections.Generic;
using MeizuSDK.Presentation;

namespace GoogleMaps.StaticMap
{
    /// <summary>
    /// 地图下载器
    /// </summary>
    class MapDownloader
    {
        /// <summary>
        /// 将图片从给定地址下载到本地磁盘
        /// </summary>
        /// <param name="fileName">保存地图图片的路径</param>
        /// <param name="url">地图图片网址</param>
        /// <returns>返回true，表示下载成功；否则表示下载失败；</returns>
        public static bool DownloadFromUrl(string fileName, string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                // 初始化网络环境
                InitializeNetwork(request);

                WebResponse response = request.GetResponse();

                using (Stream stream = response.GetResponseStream())
                {
                    if (!response.ContentType.ToLower().StartsWith("text/"))
                    {
                        return SaveBinaryFile(stream, fileName);
                    }
                }

                return false;
            }
            catch (Exception ex)
            {
                throw ex;
                //return false;
            }
        }

        /// <summary>
        /// 将二进制文件保存到指定路径
        /// </summary>
        /// <param name="inStream"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static bool SaveBinaryFile(Stream inStream, string fileName)
        {
            if (inStream == null)
                return false;

            bool result = true;
            byte[] buffer = new byte[1024];

            try
            {
                if (File.Exists(fileName))
                {
                    try
                    {
                        File.Delete(fileName);
                    }
                    catch
                    {
                        FileInfo fileInfo = new FileInfo(fileName);
                        fileInfo.Attributes = FileAttributes.Normal;

                        fileInfo.Delete();
                    }
                }

                string directory = Path.GetDirectoryName(fileName);//GetDirectoryName(fileName);

                if(!Directory.Exists(directory))
                {
                    try
                    {
                        Directory.CreateDirectory(directory);
                    }
                    catch
                    {
                        return false;
                    }
                }

                using (Stream outStream = System.IO.File.Create(fileName))
                {
                    int l;
                    do
                    {
                        l = inStream.Read(buffer, 0, buffer.Length);
                        if (l > 0)
                            outStream.Write(buffer, 0, l);
                    }
                    while (l > 0);

                    inStream.Close();
                    outStream.Close();
                }
            }
            catch(Exception ex)
            {
                //result = false;
                throw ex;
            }
            return result;
        }

        /// <summary>
        /// 初始化网络环境
        /// </summary>
        /// <param name="request"></param>
        private static void InitializeNetwork(WebRequest request)
        {
            if(Networking.Status == NetworkingStatus.None)
            {
                int errorRepeatedCount = 3;
                // 重试三次
                for (int i = 0; i < errorRepeatedCount; i++)
                {
                    if (Networking.GprsConnect(GprsAppType.Default))
                    {
                        break;
                    }
                    else
                    {
                        if (i == errorRepeatedCount - 1)
                            throw new Exception("初始化GPRS网络失败！");
                    }
                }
            }

            // 设置代理
            if (NetworkingStatus.EdgeProxy == Networking.Status)
            {
                request.Proxy = new WebProxy("10.0.0.172", 80);
            }
        }
    }
}
